#include "unixhead.h"

#include <string>
#include <vector>

#include <workflow/WFFacilities.h>
#include <workflow/RedisMessage.h>

#include <iostream>
using namespace std;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int signum)
{
    (void)signum;
    cout << "wait group done\n";
    waitGroup.done();
}

void callback(WFRedisTask * redisTask)
{
    cout << "redisTask callback is running\n";
    auto req = redisTask->get_req();
    auto resp = redisTask->get_resp();
    int state = redisTask->get_state();
    int error = redisTask->get_error();
    protocol::RedisValue value;
    switch(state){
    case WFT_STATE_SYS_ERROR:
        fprintf(stderr, "system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        fprintf(stderr, "dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        resp->get_result(value);
        if(value.is_error()) {
            fprintf(stderr, "redis error\n");
            state = WFT_STATE_TASK_ERROR;
        }
        break;
    }

    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs\n");
    }

    //遍历RedisRequest
    string cmd;
    vector<string> params;
    req->get_command(cmd);
    req->get_params(params);
    cout << "redis command: " << cmd << " ";
    for(auto & param : params) {
        cout << param << " ";
    }
    cout << endl;

    //遍历RedisResponse
    if(value.is_string()) {
        cout << "value is a string, value: " 
             << value.string_value() << endl;
    } else if(value.is_array()) {
        cout << "value is a array" << endl;
        for(size_t idx = 0; idx < value.arr_size(); ++idx) {
            cout << "arr[" << idx << "]:"
                 << value.arr_at(idx).string_value() << endl;
        }
    }
}


int main()
{
    signal(SIGINT, sighandler);

    auto redisTask = WFTaskFactory::create_redis_task("redis://127.0.0.1:6379", 0, callback);
    auto req = redisTask->get_req();
    //设置任务的属性
    req->set_request("SET", {"1", "liubei"});
    //交给框架运行
    redisTask->start();

    waitGroup.wait();//阻塞当前进程
    return 0;
}
